<template>
  <div class="list_container flex both-100">
    <breadcrumb :title="pageTitle" />
    <div class="content_container">
      <!-- 搜索模块 -->
      <el-form ref="searchMap" :inline="true" :model="searchMap" class="serach_wrapper flex-space-between">
        <div class="search">
          <el-form-item prop="userName" size="small">
            <el-input v-model="searchMap.userName" placeholder="角色名称"></el-input>
          </el-form-item>
          <el-form-item prop="phonenumber" size="small">
            <el-input v-model="searchMap.phonenumber" placeholder="权限字符"></el-input>
          </el-form-item>
          <el-form-item prop="status" style="width: 220px" size="small">
            <el-select v-model="searchMap.status" placeholder="状态">
              <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="personnelCreateTime" size="small">
            <el-date-picker v-model="searchMap.personnelCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item class="flex">
            <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
            <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
          </el-form-item>
        </div>
        <div class="edit">
          <el-form-item class="flex">
            <el-button @click="handleAdd()" class="btn_primary" icon="el-icon-plus">
              新增
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <!-- 搜索模块over -->

      <!-- 表格模块 -->
      <div class="table_container">
        <el-table :data="roleList" stripe v-loading="loading">
          <el-table-column prop="roleId" label="角色编号"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleKey" label="权限字符"></el-table-column>
          <el-table-column prop="roleSort" label="显示顺序"></el-table-column>
          <el-table-column key="status" label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column label="操作" width="170" align="center">
            <template slot-scope="scope">
              <div class="button-group">
                <span type="text" class="tag_primary" size="small" @click="handleEdit(scope.row)">编辑</span>
                <span type="text" class="tag_warning" size="small" @click="handleDelete(scope.row)">删除</span>
                <span type="text" class="tag_success" size="small" @click="handleDataScope(scope.row)">权限</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 表格模块over -->

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getList"></pagination>
      <!-- 分页over -->
    </div>

    <!-- 弹框 -->
    <el-dialog :title="title" :visible.sync="dialogVisibelRole" append-to-body>
      <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName" size="small">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey" size="small">
          <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span>
          <el-input v-model="formData.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort" size="small">
          <el-input-number v-model="formData.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id" :check-strictly="!formData.menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibelRole = false" class="btn_cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="btn_primary">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog :title="title" :visible.sync="openDataScope" append-to-body>
      <el-form :model="formData" label-width="80px">
        <el-form-item label="角色名称" size="small">
          <el-input v-model="formData.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符" size="small">
          <el-input v-model="formData.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围" size="small">
          <el-select v-model="formData.dataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="formData.dataScope == 2">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="formData.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!formData.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope" class="btn_cancel">确 定</el-button>
        <el-button @click="cancelDataScope" class="btn_primary">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeselect as MenuTreeselect, listRole, roleMenuTreeselect, getRole, addRole, updateRole, delRole,deptTreeSelectById as deptTreeSelect,dataScope  } from '@/api'
export default {
  name: 'role',
  dicts: ['sys_normal_disable'],
  data () {
    return {
      // 加载状态
      loading: true,
      // 弹框标题
      title: '',
      // 弹框显示状态
      dialogVisibelRole: false,
      // 搜索条件
      searchMap: {},
      // 日期范围
      dateRange: [],
      // 角色列表
      roleList: [],
      // 部门列表
      deptOptions: [],
      // 总条数
      total: 0,
      // 表单数据
      formData: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" }
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      // 菜单树
      menuOptions: [],
      // 菜单展开状态
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 打开数据分配
      openDataScope: false,
      
          // 数据范围选项
      dataScopeOptions: [
        {
          value: "1",
          label: "全部数据权限"
        },
        {
          value: "2",
          label: "自定数据权限"
        },
        {
          value: "3",
          label: "本部门数据权限"
        },
        {
          value: "4",
          label: "本部门及以下数据权限"
        },
        {
          value: "5",
          label: "仅本人数据权限"
        }
      ],
    }
  },
  created () {
    this.getList()
    this.getMenuTreeselect()
  },
  computed: {
    pageTitle () {
      return '角色管理'
    }
  },
  methods: {
    // 查询角色列表
    getList () {
      this.loading = true
      listRole(this.searchMap).then(res => {
        this.loading = false
        this.roleList = res.rows
        this.total = res.total
      })
    },
    /** 查询菜单树结构 */
    getMenuTreeselect () {
      MenuTreeselect().then(res => {
        this.menuOptions = res.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys () {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand (value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll (value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect (value, type) {
      if (type == 'menu') {
        this.formData.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.formData.deptCheckStrictly = value ? true : false;
      }
    },
     /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect (roleId) {
      return roleMenuTreeselect(roleId).then(res => {
        this.menuOptions = res.menus;
        return res;
      });
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.getMenuTreeselect();
      this.dialogVisibelRole = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleEdit (row) {
      this.reset();
      const roleId = row.roleId || this.ids
      const roleMenu = this.getRoleMenuTreeselect(roleId);
      getRole(roleId).then(res => {
        this.formData = res.data;
        this.dialogVisibelRole = true;
        this.$nextTick(() => {
          roleMenu.then(res => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
              this.$nextTick(() => {
                this.$refs.menu.setChecked(v, true, false);
              })
            })
          });
        });
        this.title = "修改角色";
      });
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const deptTreeSelect = this.getDeptTree(row.roleId);
      getRole(row.roleId).then(res => {
        this.formData = res.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配数据权限";
      });
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(roleId) {
      return deptTreeSelect(roleId).then(res => {
        this.deptOptions = res.depts;
        return res;
      });
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.formData.roleId != undefined) {
            this.formData.menuIds = this.getMenuAllCheckedKeys();
            updateRole(this.formData).then(res => {
              this.dialogVisibelRole = false;
              this.$message.success('修改成功');
              this.getList();
            });
          } else {
            this.formData.menuIds = this.getMenuAllCheckedKeys();
            addRole(this.formData).then(res => {
              this.$message.success('新增成功');
              this.dialogVisibelRole = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 数据权限提交按钮（数据权限） */
    submitDataScope () {
      if (this.formData.roleId != undefined) {
        this.formData.deptIds = this.getDeptAllCheckedKeys();
        dataScope(this.formData).then(res => {
          this.$message.success("成功");
          this.openDataScope = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const roleIds = row.roleId || this.ids;
      this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function () {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.message.success("删除成功");
      })
    },
    // 数据重置
    reset () {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.formData = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      // this.$refs['form'].resetFields()
    },
  }
}
</script>

<style lang="less" scoped>
.list_container {
  flex-direction: column;
  background: url("@/assets/images/home/content.png") no-repeat;
  background-size: cover;
  .content_container {
    padding: 15px 20px;
    overflow-y: scroll;
  }
  .table_container {
    margin-bottom: 25px;
  }
  .pagination_container {
    display: flex;
    justify-content: space-between;
    height: 32px;
  }
}
</style>